<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            v-for="tm in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          rows="4"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- 上传图片：action图片上传的地址   list-type：文件列表的类型  on-preview：图片预览的时候触发 on-remove：当前删除图片的时候触发 -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndattrName"
        >
          <el-option
            v-for="unSelect in unSelectSaleAttr"
            :key="unSelect.id"
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndattrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
      </el-form-item>
    </el-form>
    <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="saleAttrName" label="属性名" width="100">
      </el-table-column>
      <el-table-column
        prop="spuSaleAttrValueList"
        label="属性值名称列表"
        width="width"
      >
        <template slot-scope="{ row, $index }">
          <el-tag
            :key="tag.id"
            v-for="tag in row.spuSaleAttrValueList"
            closable
            :disable-transitions="false"
            @close="handleClose(row, $index)"
          >
            {{ tag.saleAttrValueName }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="row.inputVisible"
            v-model="row.inputValue"
            :ref="$index"
            size="small"
            @keyup.enter.native="handleInputConfirm(row)"
            @blur="handleInputConfirm(row)"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="addSaleAttrValue(row, $index)"
            >+ New Tag</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="{ $index }">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="spu.spuSaleAttrList.splice($index, 1)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      attrIdAndattrName: "", // 收集未选择的销售属性的id
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        // 三级分类的id
        category3Id: 0,
        // 描述
        description: "",
        // 收集spu图片
        spuImageList: [],
        // spu的名称
        spuName: "",
        // 品牌id
        tmId: "",
        // 平台属性和属性值的数据
        spuSaleAttrList: [],
      },
      // 存储SPU信息属性
      tradeMarkList: [], // 存储品牌信息
      spuImageList: [], // 存储spu图片的数据
      saleAttrList: [], //销售属性的数据
    };
  },
  methods: {
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // file参数：代表的是删除的那个照片
      // fileList：照片墙删除某一张图片以后
      // 收集照片墙图片的数据
      this.spuImageList = fileList;
    },
    // 照片墙图片预览的回调
    handlePictureCardPreview(file) {
      // 将图片赋值给这个属性
      this.dialogImageUrl = file.url;
      // 对话框的显示
      this.dialogVisible = true;
    },
    // 照片墙图片上传成功的钩子
    handlerSuccess(response, file, fileList) {
      // 收集图片的信息
      this.spuImageList = fileList;
    },
    // 获取数据
    async initSpuData(spu) {
      // 获取SPU信息的数据
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      // 获取品牌的信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      // 获取spu图片的数据
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data;
        // 将服务器返回的数据进行修改
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        // 把整理好的数据赋值给容器
        this.spuImageList = listArr;
      }
      // 获取平台的全部销售属性
      let saleResult = await this.$API.spu.reqBassSaleAttrList();
      if ((saleResult.code = 200)) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 添加销售属性
    addSaleAttr() {
      // 把已收集需要添加的销售属性的信息
      // 把手机的销售属性的信息进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndattrName.split(":");
      // 向SPU对象的spuSaleAttrList属性里面添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndattrName = "";
    },
    // 添加属性值按钮
    addSaleAttrValue(row, index) {
      // 点击销售属性值当中添加按钮的时候,有button转换为input
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // input失去焦点的数据
    handleInputConfirm(row) {
      row.inputVisible = false;
      const { baseSaleAttrId, inputValue } = row;
      let result = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName != inputValue
      );
      if (!result) return;
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
    },
    // 删除属性值操作
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },
    // 添加SPU || 修改SPU
    async addOrUpdateSpu() {
      // 整理参数
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if (result.code == 200) {
        this.$message({
          type: "success",
          message: "保存成功",
        });
        if (this.spu.id) {
          this.$emit("cancel",'delete');
        }else{
          this.$emit("cancel",'add');
        }
        Object.assign(this._data,this.$options.data())
      }
    },
    // 点击添加SPU发的请求
    async addSpuDate(category3Id) {
      // 获取品牌的信息
      this.spu.category3Id = category3Id
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      // 获取平台的全部销售属性
      let saleResult = await this.$API.spu.reqBassSaleAttrList();
      if ((saleResult.code = 200)) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 取消按钮的回调
    cancel(){
      this.$emit('cancel','delete')
      // 清除数据
      // 组件实例this._data,可以操作data当中的响应式
      // this.$options可以获取配置对象,配置对象的data函数执行,返回的响应式数据为空
      Object.assign(this._data,this.$options.data())
    }
  },
  computed: {
    unSelectSaleAttr() {
      // 数组的过滤方式，可以从已有的数组当中过滤出用户需要的元素，并返回一个新的数据
      let result = this.saleAttrList.filter((item) => {
        // every数组的方法，返回一个布尔值(真|假)
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
      return result;
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
